from applications.function.elv import calculate_cable_risk, calculate_risk, calculate_cable_level
from version import path


def re_data():
    T = calculate_risk(path('file', '电缆信息收集表（验证版）-望城公司.xlsx'))
    score_list = T.to_dict('records')

    _data = {}
    # 遍历列表，根据 category 字段分类
    for item in score_list:
        category = item['cable_section_number']
        if category not in _data:
            start_end = item['start_end'].split('至')

            _data[category] = {
                'cable_section_number': item['cable_section_number'],
                'line_name': item['line_name'],
                'start_end': item['start_end'],
                'start': start_end[0],
                'end': start_end[1],
                'routine_test': item['routine_test'],
                'avg_load_rate': item['avg_load_rate'],
                'max_load_rate': item['max_load_rate'],
                'operation_years': item['operation_years'],
                'three_year_faults': item['three_year_faults'],
                'three_year_other_faults': item['three_year_other_faults'],
                'cable_path': item['cable_path'],
                'cable_number': item['cable_number'],
                'path_environment': item['path_environment'],
                'avg_cable_number': item['avg_cable_number'],
                'avg_load_volume': item['avg_load_volume'],
            }
            _data[category]['cable_head_list'] = []

        _item = {
            'type': item['c1'],
            'historical_failure_rate': item['c2'],
            'construction_environment': item['c3'],
            'operation_years': item['c4'],
            'test_results': item['c5'],
            'risk_score': item['risk_score'],
            'risk_level': item['risk_level'],
        }
        _data[category]['cable_head_list'].append(_item)

    data = {
        "cable_section_data": []
    }
    for item in _data:
        _item = _data[item]
        score = [s['risk_score'] for s in _item['cable_head_list']]

        final_score = calculate_cable_risk(score)
        _item['risk_score'] = final_score
        _item['risk_level'] = calculate_cable_level(final_score)
        _item['risk_score_list'] = score
        _item['risk_level_list'] = [s['risk_level'] for s in _item['cable_head_list']]

        data['cable_section_data'].append(_item)
    return data


def rn_data():
    _data = re_data()

    data = {}

    for item in _data['cable_section_data']:
        category = item['line_name']
        if category not in data:
            data[category] = []
        data[category].append(item)

    for item in data:
        data[item] = sorted(data[item], key=lambda k: k['risk_score'], reverse=True)
    return data


if __name__ == '__main__':
    print(rn_data())
